package com.ebt.m.proposal_v2.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.LinearLayout;

import com.ebt.m.commons.utils.ActivityUtils;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.data.bean.ProposalInsurant;
import com.ebt.m.data.bean.ProposalListItem;
import com.ebt.m.data.entity.Customer;
import com.ebt.m.data.entity.ProductBridgeObj;
import com.ebt.m.data.entity.ProductInfo;
import com.ebt.m.data.middle.InsuredPerson;
import com.ebt.m.proposal_v2.bean.ArgProposalDetail;
import com.ebt.m.proposal_v2.bean.ArgProposalMake;
import com.ebt.m.proposal_v2.bean.InsuranceEntity;
import com.ebt.m.proposal_v2.ui.MakeProposalActivity;
import com.ebt.m.proposal_v2.ui.ProposalDetailActivity;
import com.ebt.m.utils.NumberHelper;
import com.ebt.m.utils.TimeUtils;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.wiki.ActProductDetail;
import com.ebt.m.wiki.view.AutoViewsFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ProposalUtils {
    //解析默认的投保选项，第一层包含items和person节点
       /* {
            "items": [
                {
                    "Value": 5,
                        "isCoverageUseAnother": "false",
                        "Index": 1,
                        "DisplayName": "交费期间",
                        "FieldName": "PaymentPeriod",
                        "ItemName": "5年交"
                },
                {
                    "Value": 30,
                        "isCoverageUseAnother": "false",
                        "Index": 0,
                        "DisplayName": "保障期间",
                        "FieldName": "CoveragePeriod",
                        "ItemName": "30年期"
                }
            ],
            "person": {
                    "sex": "0",
                    "coverage": 100000,
                    "premium": 3000,
                    "profession": 1,
                    "age": 35
            }
        }
        */


    /**
     * 格式化投保选项，用来显示
     *
     * @param jsonProductOptions
     * @param coverage
     * @param coverageUnitIsFen
     * @param premium
     * @return
     */
    public static SpannableString getText(String jsonProductOptions,
                                          double coverage, boolean coverageUnitIsFen, double premium) {
        StringBuilder builder = new StringBuilder();
        List<String> list = new ArrayList<String>();
        boolean first = true;
        String itemName = null;
        String displayName = null;
        SpannableString sp = new SpannableString("");
        try {
            // 如果存在保额取代字段，则处理
            boolean hasCoverageUseAnotherItem = false;
            //保额取代字段属性
            String isCoverageUseAnotherItem = "";
            JSONArray array = new JSONArray(jsonProductOptions);
            for (int i = 0; i < array.length(); i++) {
                JSONObject obj = array.getJSONObject(i);
                Boolean isCoverageUseAnother = obj
                        .optBoolean("isCoverageUseAnother");
                if (!isCoverageUseAnother) {
                    itemName = obj.optString("ItemName");
                    displayName = obj.optString("DisplayName");
                    if (!first) {
                        builder.append(" | ");
                    }
                    builder.append(displayName + " ");
                    list.add(builder.length() + "-" + itemName.length());
                    builder.append(itemName);
                    first = false;
                } else {
                    isCoverageUseAnotherItem = obj.optString("ItemName");
                    hasCoverageUseAnotherItem = true;
                }
            }
            //保额处理
            builder.append(" | ").append("保额 ");
            if (hasCoverageUseAnotherItem) {
                itemName = isCoverageUseAnotherItem;
            } else {
                if (coverageUnitIsFen) {
                    itemName = coverage + "份";
                } else {
                    itemName = NumberHelper.formatMoney(coverage) + "元";
                }
            }
            list.add(builder.length() + "-" + itemName.length());
            builder.append(itemName);

            //保费处理
            builder.append(" | ").append("保费 ");
            itemName = NumberHelper.formatMoney(premium) + "元";
            list.add(builder.length() + "-" + itemName.length());
            builder.append(itemName);

            //格式处理
            sp = new SpannableString(builder.toString());
            int color = Color.parseColor("#ff37ac68");
            for (String s : list) {
                String[] ss = s.split("-");
                int start = Integer.parseInt(ss[0]);
                int end = Integer.parseInt(ss[1]);
                sp.setSpan(new ForegroundColorSpan(color), start, start + end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return sp;
    }

    /**
     * 刷新计算器视图和数据
     *
     * @return void
     * @Description: 刷新计算器区域
     * @throw
     */
    public static void refreshCalcDataAndView(Context mContext, ProductBridgeObj mProductObj, LinearLayout ll_calc, ProductOptionChangeListener productOptionChangeListener) {
        ll_calc.setVisibility(View.VISIBLE);
        ll_calc.removeAllViews();
//        final InsuranceObj mInsuranceObj = mProductObj.getInsuranceObj();
        AutoViewsFactory autoViewsFactory = new AutoViewsFactory(mContext, ll_calc);
//        autoViewsFactory.generateViews(mInsuranceObj);
        autoViewsFactory.generateViews(mProductObj.getInsuranceObj());
        autoViewsFactory.setOnSettingChangedListener(new AutoViewsFactory.OnSettingChangedListener() {

            @Override
            public void onSettingChanged() {
                if (productOptionChangeListener != null) {
                    productOptionChangeListener.onProductOptionChange();
                }
            }
        });
    }

    /**
     * 投保选项改变监听
     */
    public interface ProductOptionChangeListener {
        public void onProductOptionChange();
    }

    /**
     * 对象转换
     *
     * @param proposalInsurant
     */
    public static InsuredPerson convertToInsuredPerson(ProposalInsurant proposalInsurant) {
        InsuredPerson insuredPerson = new InsuredPerson();
        insuredPerson.profession = proposalInsurant.getCareerCategory() == null ? EnumProfession.ONE.value() : proposalInsurant.getCareerCategory();
        insuredPerson.age = proposalInsurant.getAge();
        insuredPerson.sex = proposalInsurant.getSex() + "";
        insuredPerson.name = proposalInsurant.getName();
        insuredPerson.relationName = proposalInsurant.getARelationship();
        insuredPerson.birthday = proposalInsurant.getBirthday();
        return insuredPerson;
    }


    /**
     * 获取主险投保选项Items
     *
     * @return [{"DisplayName":"交费期间","FieldName":"PaymentPeriod","Value":5,"ItemName":"5年交","Index":1,"isCoverageUseAnother":"false"},{"DisplayName":"保障期间","FieldName":"CoveragePeriod","Value":30,"ItemName":"30年期","Index":0,"isCoverageUseAnother":"false"}]
     */
    public static JSONArray convertJsonStringToJsonArray(String strProductOptions) {
        try {
            return new JSONArray(strProductOptions);
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 产品是否满足被保人
     *
     * @param insuredPerson
     * @param product
     * @return error
     */
    public static String hasMeetWith(InsuredPerson insuredPerson, ProductInfo product) {
        if (!product.hasVersion()) {
            return "该产品正在维护中";
        }

        if (product == null) {
            return "请选择产品";
        }

        if (insuredPerson == null) {
            return "被保人不能为空";
        }
        String result = null;
        try {
            if (insuredPerson.birthday == null) {
                insuredPerson.birthday = TimeUtils.getBirthday(insuredPerson.age);
            }
            if (insuredPerson.birthday != null) {
                int[] minAges = getAges(product.MinAge);
                int[] maxAges = getAges(product.MaxAge);
                // 取最小年龄
                if (minAges[0] != 0) {// 取年不为0，只比较年即年龄
                    int curAge = TimeUtils.getAge(insuredPerson.birthday);
                    if (minAges[0] > curAge) {
                        result = "被保人年龄或生日不符合投保规则";
                        return result;
                    }
                } else {// 取最小年龄为0，取当前被保人的生日转换成月份，若不为0，比较月份。
                    int minMonth = minAges[1];
                    if (minMonth != 0) {
                        int months = TimeUtils.getMonthSpace(
                                insuredPerson.birthday, new Date());
                        if (minMonth > months) {
                            result = "被保人年龄或生日不符合投保规则";
                            return result;
                        }
                        // DateUtils.getMonthSpace(DateUtils.dateTime2String(insuredPerson.birthday),DateUtils.dateTime2String(new
                        // Date()));
                    } else {// 取最小月份为0，取当前被保人的生日转换成日期，若不为0，比较日期。
                        int minDays = minAges[2];
                        long days = TimeUtils.daysBetween(insuredPerson.birthday,
                                new Date());
                        if (minDays > days) {
                            result = "被保人年龄或生日不符合投保规则";
                            return result;
                        }
                    }
                }

                // 取最小年龄
                if (maxAges[0] != 0) {// 拖年不为0，只比较年即年龄
                    int curAge = TimeUtils.getAge(insuredPerson.birthday);
                    if (maxAges[0] < curAge) {
                        result = "被保人年龄或生日不符合投保规则";
                        return result;
                    }
                } else {// 取最小年龄为0，取当前被保人的生日转换成月份，若不为0，比较月份。
                    int maxMonth = maxAges[1];
                    if (maxMonth != 0) {
                        int months = TimeUtils.getMonthSpace(
                                insuredPerson.birthday, new Date());
                        if (maxMonth < months) {
                            result = "被保人年龄或生日不符合投保规则";
                            return result;
                        }
                        // DateUtils.getMonthSpace(DateUtils.dateTime2String(insuredPerson.birthday),DateUtils.dateTime2String(new
                        // Date()));
                    } else {// 取最小月份为0，取当前被保人的生日转换成日期，若不为0，比较日期。
                        int maxDays = maxAges[2];
                        long days = TimeUtils.daysBetween(insuredPerson.birthday,
                                new Date());
                        if (maxDays < days) {
                            result = "被保人年龄或生日不符合投保规则";
                            return result;
                        }
                    }
                }
            }
            if (product.AccSex != 0) {//0:男女都可以。1：仅女适用。2：仅男适用
                int sex = Integer.parseInt(insuredPerson.sex);
                if (sex + 1 != product.AccSex) {
                    result = "被保人性别不符合投保规则";
                    return result;
                }
            }
            if (insuredPerson.profession > product.AccOccupation) {
                result = "被保人职业类别不符合投保规则";
                return result;
            }
        } catch (Exception e) {
            result = "该产品正在维护中";
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 将年龄为0时的情况加入判断
     *
     * @param person
     * @param product
     * @return
     */
    public static String fitMeetWith(InsuredPerson person, ProductInfo product) {
//        int days = ProposalUtils.getMinAgeDay(product);
//        if (days > 0 && person.age == 0) {
//            Date bd = TimeUtils.dayPlusOrMinus(TimeUtils.getBirthday(person.age), -days);
//            person.birthday = bd;
//        }
        return ProposalUtils.hasMeetWith(person, product);
    }

    /**
     * 将年龄为0时的情况加入判断
     *
     * @param person
     * @param product
     * @return
     */
    public static String fitMeetWithIfAge0(InsuredPerson person, ProductInfo product) {
        int days = ProposalUtils.getMinAgeDay(product);
        if (days > 0 && person.age == 0) {
            Date bd = TimeUtils.dayPlusOrMinus(TimeUtils.getBirthday(person.age), -days);
            person.birthday = bd;
        }
        return ProposalUtils.hasMeetWith(person, product);
    }

    public static int[] getAges(String ageStr) {
        int[] ages = new int[]{0, 0, 0};
        int point = ageStr.indexOf(".");
        if (point == -1) {
            ages[0] = Integer.parseInt(ageStr);
            return ages;
        }
        String[] ss = ageStr.split("\\.");
        ages[0] = Integer.parseInt(ss[0]);
        if (ageStr.substring(point).length() < 5) {
            return ages;
        }
        ages[1] = Integer.parseInt(ss[1].substring(0, 2));
        ages[2] = Integer.parseInt(ss[1].substring(2, 5));
        return ages;
    }

    /**
     * 制作默认计划书
     * <p>点击制作计划书进入</p>
     *
     * @param context
     */
    public static void makeDefaultProposal(Context context) {
        Intent intent = new Intent(context, MakeProposalActivity.class);
        Bundle extra = new Bundle();
        ArgProposalMake arg = new ArgProposalMake();
        arg.flag = MakeProposalActivity.Flag_Default;
        extra.putSerializable(MakeProposalActivity.Arg, arg);
        intent.putExtras(extra);
        intent.putExtra(MakeProposalActivity.Finish_To_Proposal_List, true);
        context.startActivity(intent);
    }

    /**
     * 制作草稿计划书
     * <p>点击草稿进入</p>
     *
     * @param context
     * @param proposalId
     */
    public static void makeProposalWithDraft(Context context, String proposalId) {
        Intent intent = new Intent(context, MakeProposalActivity.class);
        Bundle extra = new Bundle();
        ArgProposalMake arg = new ArgProposalMake();
        arg.flag = MakeProposalActivity.Flag_Draft;
        arg.proposalId = proposalId;
        extra.putSerializable(MakeProposalActivity.Arg, arg);
        intent.putExtras(extra);
        intent.putExtra(MakeProposalActivity.Finish_To_Proposal_List, true);
        context.startActivity(intent);
    }

    /**
     * 制作带客户的计划书
     * <p>从客户进入</p>
     *
     * @param context
     * @param customerId
     */
    public static void makeProposalWithCustomer(Context context, String customerId) {
        Intent intent = new Intent(context, MakeProposalActivity.class);
        Bundle extra = new Bundle();
        ArgProposalMake arg = new ArgProposalMake();
        arg.flag = MakeProposalActivity.Flag_Customer;
        arg.customerId = customerId;
        extra.putSerializable(MakeProposalActivity.Arg, arg);
        intent.putExtras(extra);
        intent.putExtra(MakeProposalActivity.Finish_To_Proposal_List, true);
        context.startActivity(intent);
    }

    /**
     * 制作带产品的计划书
     * <p>从产品进入</p>
     *
     * @param context
     * @param product
     */
    public static void makeProposalWithProduct(Context context, ProductBridgeObj product) {
        Intent intent = new Intent(context, MakeProposalActivity.class);
        Logger.i("->从产品制作计划书\n"
                + "保费： " + DataUtils.getPremium(product).toString() + "\n"
                + "保额： " + DataUtils.getCoverage(product).toString() + "\n"
                + "保障期间： " + DataUtils.getCoveragePeriod(product).toString() + "\n"
                + "缴费期间： " + DataUtils.getPaymentPeriod(product).toString());
        Bundle extra = new Bundle();
        ArgProposalMake arg = new ArgProposalMake();
        arg.flag = MakeProposalActivity.Flag_Product;
        arg.productId = product == null ? null : String.valueOf(product.getProductId());
        arg.customer = getCustomerByProductBridge(product);
        arg.customer.setBirthday(null); // 从产品进入计划书，生日都是null

        InsuranceEntity productMain = new InsuranceEntity();
        productMain.productId = product.getProductId();
        productMain.productName = product.getProductName();
        productMain.isMain = 1;
        productMain.isBindingMain = false;
        productMain.coverage = DataUtils.getCoverage(product);
        productMain.premium = DataUtils.getPremium(product);
        productMain.coveragePeriod = DataUtils.getCoveragePeriod(product);
        productMain.paymentPeriod = DataUtils.getPaymentPeriod(product);

        /* 解析除保额、保费、保障期间、缴费期间之外的属性*/
        productMain.extraData = DataUtils.parseExtraOptions(product);

        /**
         * 如果整型的缴费期间以浮点型表示，转化为整型； 传入计算器整型与浮点型是截然不同的结果
         */
        if (productMain.paymentPeriod != null &&
                (productMain.paymentPeriod.value.endsWith(".0") || productMain.paymentPeriod.value.endsWith(".00"))) {
            productMain.paymentPeriod.value = productMain.paymentPeriod.value.substring(0, productMain.paymentPeriod.value.indexOf("."));
        }
        arg.product = productMain;

        extra.putSerializable(MakeProposalActivity.Arg, arg);
        intent.putExtras(extra);
        context.startActivity(intent);
    }

    /**
     * 跳转到计划书预览
     *
     * @param context
     * @param argProposalDetail
     */
    public static void previewProposal(Context context, ArgProposalDetail argProposalDetail) {
        Bundle extra = new Bundle();
        extra.putSerializable(ProposalDetailActivity.ArgProposalDetail, argProposalDetail);
        ActivityUtils.launchActivity(context, ProposalDetailActivity.class, extra);
    }


    /**
     * 跳转到计划书预览(跳转到原来的接口改)
     * 带有已发送标签
     *
     * @param context
     */
    public static void previewProposalWithPostFlag(Context context, String proposalId, String proposalName, String previewUrl) {
        if (TextUtils.isEmpty(proposalId) || TextUtils.isEmpty(previewUrl)) {
            UIHelper.makeToast(context, "计划书不存在");
            return;
        }
        ArgProposalDetail argProposalDetail = new ArgProposalDetail();
        argProposalDetail.proposalId = proposalId;
        argProposalDetail.proposalName = TextUtils.isEmpty(proposalName) ? "计划书" : proposalName;
        argProposalDetail.previewUrl = previewUrl;
        argProposalDetail.isNewProposal = false;
        argProposalDetail.isProposalPosted = true;
        previewProposal(context, argProposalDetail);
    }

    /**
     * 取出产品中的默认用户信息
     *
     * @param product
     * @return
     */
    private static Customer getCustomerByProductBridge(ProductBridgeObj product) {
        if (product == null || product.getPerson() == null) {
            return null;
        }
        Logger.i("->产品附带的被保人信息： \n" + product.getPerson().toString());
        Customer customer = new Customer();
        customer.setSex(TextUtils.isEmpty(product.getPerson().sex) ? 1 : Integer.valueOf(product.getPerson().sex));
        customer.setCareerCategory(product.getPerson().profession);
        customer.setAge(product.getPerson().age);
        customer.setBirthday(product.getPerson().birthday);
        return customer;
    }

    public static void gotoMakeNewProposal(Context context) {
        makeDefaultProposal(context);
    }

    /**
     * 旧版名片获取方式（从DB获取），已废弃不用
     *
     * @param context
     * @param applicantName
     * @return
     */
    /*@Deprecated
    public static String getShareContent(Context context, String applicantName) {
        StringBuffer shareContent = new StringBuffer();
        if (!TextUtils.isEmpty(applicantName)) {
            shareContent.append("敬呈：").append(applicantName).append("，");
        }

        CardInfo cardInfo = AppContext.getCurrentUser().getCardInfo();
        String agentName = null;
        if (cardInfo == null || TextUtils.isEmpty(cardInfo.getName())) {
            agentName = "我";
        } else {
            agentName = cardInfo.getName();
        }

        shareContent.append(agentName).append("为您精心设计的保险计划，敬请查阅！");
        return shareContent.toString();
    }*/

    public static String getShareContent(String applicantName, String agentUser) {
        StringBuffer shareContent = new StringBuffer();
        if (!TextUtils.isEmpty(applicantName)) {
            shareContent.append("敬呈：").append(applicantName).append("，");
        }
        if (agentUser == null || agentUser.length() == 0) {
            agentUser = "我";
        }
        shareContent.append(agentUser).append("为您精心设计的保险计划，敬请查阅！");
        return shareContent.toString();
    }


    /**
     * 产品最小投保单位是否是天，如果是则返回此天数，否则返回-1
     *
     * @param product
     * @return
     */
    public static int getMinAgeDay(ProductInfo product) {
        int result = -1;
        int[] minAges = getAges(product.MinAge);
        if (minAges[0] != 0) {// 取年不为0，只比较年即年龄
            return result;
        } else {
            int minMonth = minAges[1];
            if (minMonth != 0) {
                return result;
            } else {// 取最小月份为0，取当前被保人的生日转换成日期，若不为0，比较日期。
                int minDays = minAges[2];
                if (minDays > 0) {
                    return minDays;
                }
                return result;
            }
        }
    }

    /**
     * 从计划书列表进入具体item
     *
     * @param context
     * @param listItem
     */
    public static void gotoItemFromProposalList(Context context, ProposalListItem listItem) {
        try {
            if (listItem.status == 1) {
                makeProposalWithDraft(context, listItem.pickNum);
            } else {
                ArgProposalDetail proposalDetail = new ArgProposalDetail();
                proposalDetail.applicantName = listItem.applicantName;
                proposalDetail.proposalId = listItem.pickNum;
                proposalDetail.proposalName = listItem.proposalName;
                proposalDetail.isNewProposal = false;
                proposalDetail.previewUrl = listItem.previewUrl;
                proposalDetail.shareUrl = listItem.viewUrl;
                proposalDetail.shareUrlWeXin = listItem.viewUrl;
                if (listItem.status > 2) { /* 1 草稿 2 未发送 3已发送 4已查看 -1 全部*/
                    proposalDetail.isProposalPosted = true;
                }
                proposalDetail.isNewProposal = false;
                previewProposal(context, proposalDetail);
            }
        } catch (Exception e) {
            Logger.e(e);
        }
    }

    /**
     * 从制作计划书的产品资料列表 -> 产品详情（新版）
     *
     * @param context
     * @param productId
     */
    public static void startProductDetailNewFromProposalMaking(Context context, int productId) {
        Bundle bundle = new Bundle();
        bundle.putInt("productId", productId);
        ActivityUtils.launchActivity(context, ActProductDetail.class, bundle);
    }

    /**
     * 从首页制作计划书
     *
     * @param context
     * @param productId
     */
    public static void startMakingProposalFromDynamic(Context context, int productId) {
        Bundle extra = new Bundle();
        ArgProposalMake arg = new ArgProposalMake();
        arg.flag = MakeProposalActivity.Flag_Dynamic;
        arg.productId = productId + "";
        extra.putSerializable(MakeProposalActivity.Arg, arg);
        Intent intent = new Intent(context, MakeProposalActivity.class);
        if (extra != null) {
            intent.putExtras(extra);
        }
        intent.putExtra(MakeProposalActivity.Finish_To_Proposal_List, true);
        context.startActivity(intent);
    }
}
